package ga.cross;

import ga.GARun;
import ga.individuals.Individual;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import com.mathworks.toolbox.javabuilder.MWException;
import com.mathworks.toolbox.javabuilder.MWNumericArray;

public class Segment implements CrossMethod {
	private final static double pUniformCross = 0.6;
	
	@Override
	public Collection<Individual> method(Collection<Individual> individuals) throws MWException {
		if (individuals.size() != 2) {
			return null;
		}
		
		List<Individual> listIndividuals = new LinkedList<Individual>(individuals);
		
		// prepara los hijos
		double[] childrenChromosomeOne = new double[GARun.networkWeightSize];
		double[] childrenChromosomeTwo = new double[GARun.networkWeightSize];
		
		// obtiene los padres a cruzar
		double[] chromosomeOne = (double[])listIndividuals.get(0).getIndividualValue().getDoubleData();
		double[] chromosomeTwo = (double[])listIndividuals.get(1).getIndividualValue().getDoubleData();
		
		Random r = new Random(System.currentTimeMillis());
		
		for (int i = 0; i < GARun.networkWeightSize; i++) {
			if (r.nextDouble() >= pUniformCross) {
				childrenChromosomeOne[i] = chromosomeOne[i];
				childrenChromosomeTwo[i] = chromosomeTwo[i];
			} else {
				childrenChromosomeOne[i] = chromosomeTwo[i];
				childrenChromosomeTwo[i] = chromosomeOne[i];
			}
		}
		List<Individual> offsprings = new LinkedList<Individual>();
		offsprings.add(new Individual(new MWNumericArray(childrenChromosomeOne)));
		offsprings.add(new Individual(new MWNumericArray(childrenChromosomeTwo)));
		return offsprings;
	}
}
